// miniprogram/pages/backgroud/background.js
import {
  getBackground,
  delBackground,
  selectBackground,
  getBackgroundCount
} from './../../api/backgroud.js'

const util = require('../../utils/util.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    btns: [{
      src: 'https://636c-cloud1-8g4peis6c08f195c-1306096204.tcb.qcloud.la/icon-delete.png?sign=f87397119820b785808793a5f751693f&t=1627716272',
      text: "删除"
    }],
    list: [],
    showLoading: false,
  },
  onLoad(options) {
    Promise.all([getBackgroundCount(), getBackground(0, 8)]).then(res => {
      this.data.totalSize = res[0].total
      const list = res[1].data

      this.setData({
        list: list,
        isLoadMore: this.isLoadMore()
      }, () => {
        //渲染完成
        console.log("渲染完成")
        this.checkShowLoading()
      })
    })
  },
  checkShowLoading() {
    const query = wx.createSelectorQuery()
    query.select(".body").boundingClientRect().exec(res => {

      const {
        height
      } = res[0]
      const {
        windowHeight
      } = wx.getSystemInfoSync()
      const showLoading = height >= windowHeight
      this.setData({
        showLoading: showLoading,
      })
    })
  },
  //是否加载更多
  isLoadMore() {
    const skip = this.data.list.length
    return this.data.totalSize > skip
  },
  //删除
  deleteClick(e) {
    console.log("delete", e)

    const len = this.data.list.length
    if (len == 1) {
      wx.showToast({
        title: '至少要有张背景',
        icon: "error"
      })
      return
    }
    const index = e.currentTarget.dataset.index
    const id = e.currentTarget.dataset.id
    const item = this.data.list[index]
    const that = this
    wx.showModal({
      title: '确定要删除当前背景?',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          })
          delBackground(id, item.fileId).then(res => {
            //删除了数量-1
            that.data.totalSize--
            //删除
            that.data.list.splice(index, 1)

            that.setData({
              list: that.data.list,
              isLoadMore: that.isLoadMore()
            },()=>{
              that.checkShowLoading()
            })
            wx.hideLoading()

            util.navigateBackResult({
              data: {
                'selectBg': that.data.list[0]
              },
              back: false
            })

          })
        }
      }
    })
  },
  onSelect(e) {
    //选择
    const index = e.currentTarget.dataset.index
    const id = e.currentTarget.dataset.id
    if (index === 0) {
      wx.showToast({
        title: '当前已是选中背景了',
        icon: "error"
      })
      return
    }

    wx.showModal({
      title: "是否要替换背景?"
    }).then(res => {
      if (res.confirm) {
        wx.showLoading({
          title: '替换中...',
        })
        selectBackground(id).then(res => {
          wx.hideLoading()
          this.data.list.splice(index, 1)
          this.data.list.unshift(res.data)
          this.setData({
            list: this.data.list
          })

          wx.showModal({
            title: "替换成功是否返回?",
            confirmText: "返回"
          }).then(res => {
            let back = null
            if (res.confirm) {
              back = true
            } else {
              back = false
            }
            util.navigateBackResult({
              data: {
                'selectBg': this.data.list[0]
              },
              back: back
            })
          })

        })
      }
    })

  },
  //分页
  onReachBottom() {

    if (this.isLoadMore()) {
      getBackground(this.data.list.length, 8).then(res => {
        let index = this.data.list.length
        let changeData = {}
        res.data.forEach(item => {
          changeData['list[' + (index++) + ']'] = item
        })
        console.log("changeData", changeData)
        changeData['isLoadMore'] = this.isLoadMore()
        this.setData(changeData)
      })

    } else {
      console.log("到底了")
      this.setData({
        isLoadMore: false
      })
    }


  },
  onSlideShow(e) {
    console.log("onSlideShow", e)
    const index = e.currentTarget.dataset.index
    const currentSlideShow = 'list[' + index + '].slideShow'
    const preSlideShow = this.data.currentSlideShow
    if (preSlideShow) {
      this.setData({
        [preSlideShow]: false
      })
    }
    this.setData({
      currentSlideShow: currentSlideShow,
      [currentSlideShow]: true
    })
  },
  onRootTouchStart(e) {
    const preSlideShow = this.data.currentSlideShow
    if (preSlideShow) {
      this.setData({
        [preSlideShow]: false,
        currentSlideShow: null
      })
    }
  },

})